package com.example.demo.util;

import com.alibaba.fastjson.JSONObject;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 * @Author: huanggaotao
 * @Description:
 * @Date: Created in 16:14 2021/4/19
 * @Modified By:
 */
public class Jwtshouxie {
    private static String SING_KEY = "hgt";


    public static void main(String[] args) throws UnsupportedEncodingException {

        //手写Jwt 封装三个部分 header、payload、sign 签名值

        JSONObject header = new JSONObject();

        header.put("alg","HS256");

        JSONObject payload = new JSONObject();

        payload.put("phone","135*****590");

        //头部
        String headerEncoded = Base64.getEncoder().encodeToString(header.toJSONString().getBytes());

        //身体
        String payLoadJsonStr = payload.toJSONString();
        String payloadEncoded = Base64.getEncoder().encodeToString(payLoadJsonStr.getBytes());

        //sign签名值  实际上就base64的payload+盐值的md5加密
        String sign = DigestUtils.md5Hex(headerEncoded+payloadEncoded+SING_KEY);


        String jwt = headerEncoded+"."+payloadEncoded+"."+sign;
        System.out.println(payloadEncoded);
        System.out.println(jwt);
        //eyJhbGciOiJIUzI1NiJ9.eyJwaG9uZSI6IjEzNSoqKioqNTkwIn0.mXdtqlHZwgNAHansoEZooDPmEKW9PxbqVk0m6DuMAko



        //解密


        //获取payload部分的数据
        byte[] payLoadEncode = jwt.split("\\.")[1].getBytes();
        String s = new String(payLoadEncode);
        //将payload部分通过base64解码
        String payLoadDecoder = new String(Base64.getDecoder().decode(payLoadEncode), "UTF-8");

        System.out.println(payLoadDecoder);

        //生成加密之后的签名值
        String newSing = DigestUtils.md5Hex(headerEncoded+s + SING_KEY);

        //比对签名值是否一样
        boolean equals = newSing.equals(jwt.split("\\.")[2]);

        //true  表示 jwt在有效期范围内，并且整个payload数据没有被篡改
        System.out.println(equals);


    }



}
